package com.abe.libquick.api;


import androidx.annotation.IntDef;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Type;
import java.util.Date;

public class JsonHelper {
    //按照日期转换区分
    public static final int JSON_NORMAL = 1;//普通Gson
    public static final int JSON_C_SHAPE = 2;//C# gson

    public static Gson gson(@JsonType int type) {
        GsonBuilder builder = new GsonBuilder();
        switch (type) {
            case JSON_NORMAL:
                break;
            case JSON_C_SHAPE:
                builder.registerTypeAdapter(Date.class, new GsonCustomerDateJsonSerializer());
                break;
        }
        return builder.serializeNulls().create();
    }

    @IntDef({JSON_NORMAL, JSON_C_SHAPE})
    @Retention(RetentionPolicy.SOURCE)
    public @interface JsonType {
    }

    static class GsonCustomerDateJsonSerializer implements JsonSerializer<Date>, JsonDeserializer<Date> {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(StringSmallUtils.DateToSpecialString(src));
        }

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return StringSmallUtils.SpecialStringToDate(json.getAsString());
        }
    }
}